package com.server.questionbank.snframe.controller.Login;

import com.server.questionbank.snframe.controller.Login.entity.RegisterData;
import com.server.questionbank.snframe.domain.ResDTO.ResponseResult;
import com.server.questionbank.snframe.service.UsersService.RegisterService;
import com.server.questionbank.snframe.service.UsersService.UsersService;
import com.server.questionbank.snframe.service.VerificationCode.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/register")
public class RegisterController {
    @Autowired
    private RegisterService registerService;
    @Autowired
    private UsersService usersService;
    @Autowired
    VerificationCodeService verificationCodeService;

    // 手机号注册
    @PostMapping("/phoneRegister")
    public ResponseResult<String> phoneRegister(@RequestBody RegisterData registerData) {
        try {
            if (registerData.getPhoneNumber() == null || registerData.getPassword() == null) {
                return ResponseResult.error("手机号或密码不能为空");
            }
            if (registerData.getPhoneCode() == null) {
                return ResponseResult.error("验证码不能为空");
            }
            if (registerData.getUsername() == null) {
                return ResponseResult.error("用户名不能为空");
            }
            // 判断手机号是否已经注册
            if (usersService.selectUserByPhoneNumber(registerData.getPhoneNumber()) != null) {
                return ResponseResult.error("手机号已经注册");
            }
            // 验证验证码
            ResponseResult<String> checkSmsCode = verificationCodeService.checkSmsCode(registerData.getPhoneNumber(), registerData.getPhoneCode());
            if (checkSmsCode.getCode() != 200) return ResponseResult.error(checkSmsCode.getMessage());

            // 注册
            registerService.phoneRegister(registerData.getPhoneNumber(), registerData.getPassword(), registerData.getUsername(), registerData.getAvatar());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error(e.getMessage());
        }
        return ResponseResult.success("注册成功");
    }
}
